<?php
namespace App\Admin\Controllers\Common;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class Common extends Controller {
	public function __construct() {

	}

	/**
	 * [导出为excel]
	 * @param $data	array (二维)
	 * @param
	 *	$opt = [
	 *		'header' => array(一维),
	 *		'save_path' => string,
	 *		'file_name' => string,
	 *		'sheetname' => string
 	 *	];
	 */
	public static function exportToExcel($data,$opt) {
		$excel = new \PHPExcel();
		//横向单元格标识
		$cellName = [
			'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
			'O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB',
			'AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN',
			'AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
		];
		$excel->getActiveSheet(0)->setTitle($opt['sheetname']);
		$_row = 0;   //设置纵向单元格标识
		if($opt['header']){
			$_row++;
			$i = 0;
			//设置列标题
			foreach($opt['header'] as $v){
				$excel->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
				$i++;
			}
			$_row++;
		}
		//填写数据
		if($data){
			$i = 0;
			foreach($data as $_v){
				$j = 0;
				foreach($_v as $_cell){
					$excel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
					$j++;
				}
				$i++;
			}
		}
		//文件名处理
		if (!is_dir($opt['save_path'])) {
		   mkdir(iconv("UTF-8", "GBK", $opt['save_path']), 0777, true);
	   	}
		if(!$opt['file_name']){
			$opt['file_name'] = uniqid(time(),true);
		}
		$opt['file_name'] = iconv("utf-8", "GBK", $opt['file_name']).'.xls';
		$excelWrite = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
		$opt['save_path'] = $opt['save_path'].$opt['file_name'];
		if(is_file($opt['save_path'])){
			unlink($opt['save_path']);
		}
		$excelWrite->save($opt['save_path']);
		unset($excelWrite);
		unset($excel);
		return $opt['file_name'];
	}
}
